﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using Aliphant.Interfaces;

namespace Aliphant.Script.Models
{
    public class ScriptTools : IScriptTool
    {
        public static ScriptTools? _instance;
        public static ScriptTools Instance => _instance ?? (_instance = new ScriptTools());

        private IDictionary<string, Interval> _taskList = new Dictionary<string, Interval>();
        private CancellationTokenSource cts = new CancellationTokenSource();
        private object locker = new object();

        public ScriptTools()
        {
            Timer();
        }

        public string SetInterval(dynamic action, int timeout)
        {
            string guid = Guid.NewGuid().ToString();
            lock (locker)
            {
                _taskList.Add(guid, new Interval(() => action(), timeout));
            }

            return guid;
        }

        public void ClearInterval(string id)
        {
            lock (locker)
            {
                _taskList.Remove(id);
            }
        }

        public void ClearIntervalAll()
        {
            lock (locker)
            {
                _taskList.Clear();
            }
        }

        private void Timer()
        {
            Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    foreach (var task in _taskList.Values)
                    {
                        lock (locker)
                        {
                            if ((DateTime.Now - task.lastTime).TotalMilliseconds >= task.timeout)
                            {
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    task.action.Invoke();
                                });
                                task.lastTime = DateTime.Now;
                            }
                        }
                    }
                }
            });
        }

        private bool disposedValue;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                }

                ClearIntervalAll();
                cts.Cancel();
                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~ScriptTools()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}
